package jwlee.testthread;

public class DemoThread implements Runnable {

	public DemoThread() {
		TestThread testthread1 = new TestThread(this, "testthread1");
		TestThread testthread2 = new TestThread(this, "testthread2");
		TestThread testthread3 = new TestThread(this, "testthread3");
		testthread2.start();
		testthread3.start();
		testthread1.start();
	}

	public static void main(String[] args) {
		DemoThread demoThread1 = new DemoThread();
	}

	public void run() {
		TestThread t = (TestThread) Thread.currentThread();
		try {
			if (!"testthread1".equals(t.getName())) {
				synchronized (this) {
					System.out.println(t.getName() + " is waiting");
					wait();
				}
			}

			while (true) {
				System.out.println(t.getName() + ": time=" + t.increaseTime());

				if (t.getTime() % 10 == 0) {
					synchronized (this) {
						System.out.println("**********************");
						System.out.println(t.getName() + " notify the first thread in wait queue");
						notify();
						if (t.getTime() == 100) {
							break;
						}
						wait();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class TestThread extends Thread {
	private int time = 0;

	public TestThread(Runnable r, String name) {
		super(r, name);
	}

	public int getTime() {
		return time;
	}

	public int increaseTime() {
		return ++time;
	}
}